package main

import "sync"

var CManager = &ClientManager{
	Register:      make(chan *Client),
	Unregister:    make(chan *Client),
	userMapClient: new(sync.Map),
}

type ClientManager struct {
	Register      chan *Client
	Unregister    chan *Client
	userMapClient *sync.Map
}

func (manager *ClientManager) Start() {
	for {
		select {
		case conn := <-manager.Register:
			manager.addClient(conn)
		case conn := <-manager.Unregister:
			manager.delClient(conn)
		}
	}
}

func (manager *ClientManager) addClient(client *Client) {
	manager.userMapClient.Store(client.UserId, client)
}

func (manager *ClientManager) delClient(client *Client) {

	manager.userMapClient.Delete(client.UserId)
	client.LeaveRoom()

	close(client.Send)
	client.Socket.Close()
}
